export * from "./gd";
import { def, format, isObj, next, pd, request, msg } from "./gd";
const devQR = { img: "/static/img/qr.jpg", tip: "测试期间模拟二维码" };

let me = def.user;
export const api = {
  loginWait: 0,
  s: { /** 分销 */ distribution: false, /** 代金券 */ voucher: false, },
  get me() { return me; }, set me(p: sql.user) {
    me = p;
    uni.$on("me", () => { console.log("发送了me事件"); });
  },
  get mid() { if (!this.me.id) { login(); }; return this.me.id; }, gk: [] as string[],
  get token() { return uni.getStorageSync("token"); }, set token(p: string) { uni.setStorageSync("token", p); },
  /** 绑定微信 */
  async bindWx() { return devQR; },
  /** 提现 */
  async withdrawal(_money: number) { return devQR; },
  /** 刷新me */
  async refreshMe() { this.me = await format.user(await request("user/me")); },
  /** 修改用户信息 */
  async changeUser(user: Partial<sql.user> & { id: string; }) {
    if (await request("user/update", user)) {
      await this.refreshMe();
      msg("修改用户信息成功", "success");
    }
  },
  addPermission(perData: Uint8Array, perName: gt.gl.pdk) {
    const p = pd[perName];
    if (p) { perData[p.i] |= p.v; }
    return perData;
  },
  removePermission(perData: Uint8Array, perName: gt.gl.pdk) {
    const p = pd[perName];
    if (p) { perData[p.i] &= ~p.v; }
    return perData;
  },
  login(param: { username: string, password: string; timeout?: number; } | string) {
    return new Promise<sql.user>(async (resolve) => {
      let data: any;
      if (typeof param === "string") {
        data = (await request("/wxLogin", { code: param }));
      } else {
        data = (await request("/login", param));
      }
      if (isObj(data.data) && data.id) {
        data = data.data;
      }
      if (typeof data === "string") {
        api.token = data;
        await login();
      }
      if (isObj(data)) {
        api.token = data.token;
        api.me = await format.user(data);
      }
      resolve(api.me);
    });
  },
  reg(data: { username: string; password: string; name: string; }) {
    return new Promise<string>(async (resolve) => {
      const res = await request("/reg", data);
      if (typeof res.data.data.token === "string") {
        localStorage.setItem("token", res.data.data.token);
      }
      resolve(res.data.data);
    });
  },
  logout() {
    if (api.token) { uni.removeStorageSync("token"); }
    reLaunch("/login");
  },
};
export async function login() {
  while (api.loginWait) { await next(); }
  api.loginWait = 1;
  if (api.token && !api.me.id) {
    try {
      await setMe(await request("user/me"));
    } catch (_) { }
  }
  // #ifdef MP-WEIXIN
  if (!api.token) {
    await setMe(await request("wxLogin", await uni.login({ provider: "weixin", onlyAuthorize: true, }), null, 1));
  }
  // #endif
  if (!api.token) {
    uni.navigateTo({ url: "/pages/login" });
  }
  api.loginWait = 0;
}
export function reLaunch(url: string, params?: obj) {
  return new Promise<void>(async (resolve, reject) => {
    try {
      await uni.reLaunch({ url: upq(url, params) });
      while (true) {
        const a = getCurrentPages();
        if (a.length > 0) {
          // @ts-ignore
          const p: string = a[a.length - 1].$page?.fullPath;
          if (p) { break; }
        }
        await next();
      }
      resolve();
    } catch (error) {
      reject(error);
    }
  });
}
async function setMe(pme?: sql.user) {
  api.me = await format.user(pme);
  api.token = api.me.token;
}
export function upq(url: string, params?: obj) {
  if (params) {
    const s = Object.keys(params).map(k => `${k}=${params[k]}`).join("&");
    if (s) { url += `?${s}`; }
  };
  return url;
}
